package com.xue;

import com.pi4j.Pi4J;
import com.pi4j.io.serial.FlowControl;
import com.pi4j.io.serial.Parity;
import com.pi4j.io.serial.Serial;
import com.pi4j.io.serial.StopBits;
import com.pi4j.util.Console;


/**
 * 树莓派4b串口
 *
 * @author xuejingbao
 * @create 2023-10-10 17:22
 */
public enum Pi4bSerial {

    INSTANCE;

    public void init() throws InterruptedException {
        var console = new Console();
        var pi4j = Pi4J.newAutoContext();

        var serial = pi4j.create(Serial.newConfigBuilder(pi4j)
                .use_9600_N81()
                .dataBits_8()
                .parity(Parity.NONE)
                .stopBits(StopBits._1)
                .flowControl(FlowControl.NONE)
                .id("my-serial")
                .device("/dev/serial0")
                .provider("pigpio-serial")
                .build());
        serial.open();


        // Wait till the serial port is open
        console.print("Waiting till serial port is open");
        while (!serial.isOpen()) {
            Thread.sleep(250);
        }

        // Start a thread to handle the incoming data from the serial port
        SerialReader serialReader = new SerialReader(console, serial);
        Thread serialReaderThread = new Thread(serialReader, "SerialReader");
        serialReaderThread.setDaemon(true);
        serialReaderThread.start();

        while (serial.isOpen()) {
            Thread.sleep(500);
        }

        serialReader.stopReading();

    }

    public void addListener() {

    }

    public void sendMessage() {

    }

}
